﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using STSdb.General.Collections;
using STSdb.General.Buffers;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace STSdb.Persist
{
    public class StructureIndexerPersist<T> : IIndexerPersist<T>
        //where T: struct
    {
        //Debug.Assert(StructurePrimitives.CanConvertStructToByteArray(typeof(T)));
        
        public void Store(BinaryWriter writer, IIndexer<T> values)
        {
            Type type = typeof(T);
            int size = Marshal.SizeOf(type);
            byte[] buffer = new byte[size];

            for (int i = 0; i < values.Count; i++)
            {
                StructurePrimitives.StructToByteArray(values[i], buffer);
                writer.Write(buffer);
            }
        }

        public void Load(BinaryReader reader, IIndexer<T> values)
        {
            Type type = typeof(T);
            int size = Marshal.SizeOf(type);
            byte[] buffer = new byte[size];

            for (int i = 0; i < values.Count; i++)
            {
                reader.Read(buffer, 0, size);
                object obj = StructurePrimitives.ByteArrayToStruct(buffer, type);
                values[i] = (T)obj;
            }
        }
    }
}
